<?php

namespace App\Http\Controllers\Web\Table;

use App\Enum\enum_wechat;
use App\Http\Controllers\Api\ApiBaseController;
use App\Http\Format\FormatBase;
use App\Models\ForbidModel;
use App\Models\PosterModel;
use App\Models\SysUserModel;
use App\Models\TableItemModel;
use App\Models\TableModel;
use App\Models\TagsModel;
use App\Services\Web\TableService;
use App\Services\Web\UserService;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class TableController extends ApiBaseController
{

    /**
     * 表单维护列表/预览列表
     * @return object|null
     */
    public function table(Request $request): object
    {
        $params = $request->only([]);

        $list = TableModel::getUserData();

        foreach ($list as &$value){

            $value['created_at'] = date('Y-m-d H:i:s', $value['created_at']);
            $value['updated_at'] = date('Y-m-d H:i:s', $value['updated_at']);

            unset($value['content'], $value['deleted_at'], $value['content_insert'], $value['created_at'], $value['updated_at']);
        }

        return $this->codeSuccess($list);
    }

    /**
     * 表单维护列表-查看模板
     * @return object|null
     */
    public function table_template(Request $request): object
    {
        $params = $request->only(['id']);

        if (empty($params['id'])) {
            return $this->codeError();

        }

        //获取表单item
        $where[] = ['id', '=', $params['id']];
        $info = TableModel::getUserOne($where);

        $info['content_insert'] = json_decode($info['content_insert'], true);
        if (empty($info['content_insert'])){
            return $this->codeSuccess();

        }


        //查询content_insert所有值
        $ids = [];
        foreach ($info['content_insert'] as $value){
            if (is_array($value)){
                foreach ($value as $vs){
                    $ids[] = $vs;
                }
            }else{
                $ids[] = $value;

            }
        }


        //查询
        $list = TableItemModel::getUserData([], 'id', $ids);
        //id赋值到key上
        $list = array_column($list, null, 'id');

        //获取模板
        $tmp = enum_wechat::TEMP;
        $infoMsg = $tmp[$info['msg']];

        //根据title换参数
        foreach ($info['content_insert'] as $keys => $value){
            $artTemp = '';
            if (is_array($value)){
                foreach ($value as $vs){
                    if (!empty($list[$vs]['title'])){
                        $artTemp .= ',' . $list[$vs]['title'];
                    }
                }
                $artTemp = trim($artTemp, ',');
            }else{
                $artTemp = $list[$value]['title'];
            }

//            $infoMsg = str_replace("TITLE", $artTemp ?? '', $infoMsg, $c);
            $infoMsg = preg_replace('/TITLE/', $artTemp ?? '', $infoMsg, 1);

        }

        return $this->codeSuccess(['info_msg'=> $infoMsg]);
    }

    /**
     * 预览表单/表单展示
     * @return object|null
     */
    public function item(Request $request): object
    {
        $params = $request->only(['id']);

        if (empty($params['id'])) {
            return $this->codeError();

        }

        //获取表单item
        $where[] = ['id', '=', $params['id']];
        $info = TableModel::getUserOne($where);

        $info['content'] = json_decode($info['content'], true);
        if (empty($info['content'])){
            return $this->codeSuccess();

        }

        //查询item，根据sort排序
        $list = TableItemModel::getUserData([], 'id', $info['content']);

        foreach ($list as &$value){
            $value['option_content'] = json_decode($value['option_content'], true);
            $value['accessory_style'] = json_decode($value['accessory_style'], true);

            $value['created_at'] = date('Y-m-d H:i:s', $value['created_at']);
            $value['updated_at'] = date('Y-m-d H:i:s', $value['updated_at']);

            unset( $value['deleted_at']);
        }


        return $this->codeSuccess($list);

    }

    /**
     * 编辑/添加表单
     */
    public function item_update(Request $request): object
    {
        $params = $request->only(['id', 'title', 'status', 'content']);

        if (empty($params)) {
            return $this->codeError();

        }

        $tableInfo = [];
        //标题
        if (!empty($params['title'])) {
            $tableInfo['title'] = $params['title'];
        }

        //状态
        if (!empty($params['status'])) {
            $tableInfo['status'] = $params['status'];
        }

        //内容插入数据
        if (!empty($params['content_insert'])) {
            $tableInfo['content_insert'] = json_encode($params['content_insert']);
        }

        $list = [];
//        DB::beginTransaction();
//        try {
            //编辑表单
            $titleArr = [];
            foreach ($params['content'] as $value) {
                //验证标签名称是否重复
                if (in_array($value['title'], $titleArr)){
                    //重复
                    DB::rollBack();
                    return $this->codeError([], 3001, '标签名称重复');

                }
                $titleArr[] = $value['title'];

                if (empty($value)) {
                    continue;
                }

                //处理参数
                unset($id, $title, $data);
                list($id, $title, $data) = TableService::getInstance()->handleItemParams($value);

                //添加/修改item数据
                $id = TableService::getInstance()->databaseItem($id, $data);

                //获取表单content数据
                $list[] = $id;

                if(!empty($value['child']))
                {
                    foreach ($value['child'] as $vs){
                        unset($vsId);
                        $vs['pid'] = $id;
                        list($vsId, $vsTitle, $vsData) = TableService::getInstance()->handleItemParams($vs);
                        //添加/修改item数据
                        $vsId = TableService::getInstance()->databaseItem($vsId, $vsData);

                        $list[] = $vsId;
                    }
                }
            }

            //表单
            if (!empty($list)) {
                $tableInfo['content'] = json_encode($list);

            }

            //添加还是修改
            TableService::getInstance()->databaseTable($params['id'] ?? 0, $tableInfo);

//            DB::commit();

//        } catch (Exception $e) {
//            DB::rollBack();
//            return $this->codeError([], 3001, '事务错误');
//
//        }

        return $this->codeSuccess();

    }

    /**
     * 表单模板变量列表
     * @return object|null
     */
    public function table_params(Request $request): object
    {
        $params = $request->only(['id']);

        if (empty($params['id'])) {
            return $this->codeError();

        }

        //获取表单item
        $where[] = ['id', '=', $params['id']];
        $info = TableModel::getUserOne($where);

        $info['content'] = json_decode($info['content'], true);
        if (empty($info['content'])){
            return $this->codeSuccess();

        }

        //查询item，根据sort排序
        $list = TableItemModel::getUserData([], 'id', $info['content']);

        $data = [];
        foreach ($list as $value){
            unset($temp);
            $temp['id'] = $value['id'];
            $temp['title'] = $value['title'];
            $data[] = $temp;
        }

        return $this->codeSuccess($data);

    }

    public function table_update(Request $request): object
    {
        $params = $request->only(['id', 'item_id']);

        if (empty($params['id']) || empty($params['item_id'])) {
            return $this->codeError();

        }

        TableModel::updateSingle(['id'=> $params['id']], ['content_insert'=> json_encode($params['item_id'])]);

        return $this->codeSuccess();
    }

    /**
     * 标签维护
     * @return object|null
     */
    public function tag(Request $request): object
    {
        $params = $request->only(['is_tag']);
        $tag = TagsModel::getUserData();
        $tag = makeTreeByNum($tag, 'id', 'parent_id', 'children');

//        if (!empty($params['is_tag'])){
//            $tag_colum = array_column($tag, null, 'id');
//            $tag_temp = [];
//            $tag_temp_arr = [];
//            foreach ($tag as $value){
//                if (!in_array($value['id'], $tag_temp_arr)){
//                    if (!empty($tag_colum[$value['query_id']])){
//                        if ($value['query_id'] == $value['id']){
//                            $tag_temp[] = $value;
//                        }else{
//                            $value['name'] = $value['name'] . '/' . $tag_colum[$value['query_id']]['name'];
//                            $value['children'] = array_merge($value['children'], $tag_colum[$value['query_id']]['children']);
//                            $tag_temp_arr[] = $value['query_id'];
//                            $tag_temp[] = $value;
//                        }
//                    }
//                }
//            }
//        }else{
            $tag_temp = $tag;
//        }

        return $this->codeSuccess($tag_temp);

    }

    /**
     * 标签维护-添加/修改
     * @return object|null
     */
    public function tag_update(Request $request): object
    {
        $params = $request->only(['id','name','parent_id','sort_order','is_show','style']);

        if (empty($params)){
            return $this->codeError([], 1022, '参数错误');

        }

        //判断标签名称去重
        $whereNotId = [];
        $whereOrOne = [];
        if (!empty($params['id'])) {
            $whereNotId = [$params['id']];
        }

        if (!empty($params['name'])) {
            $whereOrOne = $params['name'];
        }

        $tagTran = TagsModel::getOneByDeWeight($whereNotId, $whereOrOne);
//        if (!empty($tagTran)) {
//            return $this->codeError([], 1002, '标签名称重复！');
//
//        }

        //获取 parent_id 最上级

        //数据库操作
        if (!empty($params['id'])){
            //修改
            $params['updated_at'] = time();
            $params['parent_id_path'] = $this->handle_best_parent_id($params['id']);
            TagsModel::updateSingle(['id'=> $params['id']], $params);

        }else{
            //新增
            $params['created_at'] = time();
            $id = TagsModel::insertSingle($params);

            $params['parent_id_path'] = $this->handle_best_parent_id($id);
            TagsModel::updateSingle(['id'=> $id], $params);
        }

        return $this->codeSuccess();

    }

    public function handle_best_parent_id($parent_id)
    {
        $tag = TagsModel::getSingle(['id'=> $parent_id]);
        if (empty($tag['parent_id'])){
            //最大级
            return $tag['id'];
        }

        return $this->handle_best_parent_id($tag['parent_id']);
    }

    /**
     * 标签维护-查看标签
     * @return object|null
     */
    public function tag_item(Request $request): object
    {
        $params = $request->only(['id']);

        if (empty($params['id'])) {
            return $this->codeError();

        }

        $where[] = ['style', '=', 2];
        $where[] = ['parent_id', '=', $params['id']];
        $tag = TagsModel::getUserData($where);
        return $this->codeSuccess($tag);

    }

    /**
     * 标签维护-删除标签
     * @return object|null
     */
    public function tag_delete(Request $request): object
    {
        $params = $request->only(['id']);

        if (empty($params['id'])){
            return $this->codeError([], 1024, '参数错误');

        }

        //查询下面是否有标签
        $where[] = ['parent_id', '=', $params['id']];
        $tag = TagsModel::getUserData($where);
        if(!empty($tag)){
            return $this->codeError([], 1024, '有下级标签，不可删除');
        }

        //用户管理添加/修改
        $delete['deleted_at'] = time();
        TagsModel::updateSingle(['id'=> $params['id']], $delete);
        return $this->codeSuccess();

    }

    /**
     * 编辑/添加表单
     */
    public function update_table_status(Request $request): object
    {
        $params = $request->only(['id', 'status']);

        if (empty($params['id']) || empty($params['status'])) {
            return $this->codeError();

        }

        //状态
        $tableInfo['status'] = $params['status'];

        DB::beginTransaction();
        try {
            TableService::getInstance()->database($params['id'], $tableInfo);
            DB::commit();

        } catch (Exception $e) {
            DB::rollBack();
            return $this->codeError([], 3001, '事务错误');

        }

        return $this->codeSuccess();

    }

    /**
     * 标签维护
     * @return object|null
     */
    public function poster(Request $request): object
    {
        $params = $request->only(['style', 'page', 'limit']);
        if (empty($params['style'])) {
            return $this->codeError();

        }

        $tag = PosterModel::getPage(['style'=> $params['style'], 'deleted_at'=> 0], $params['limit'] ?? 15);

        return $this->codeSuccess(FormatBase::listData($tag));
    }

    /**
     * 标签维护-添加/修改
     * @return object|null
     */
    public function poster_update(Request $request): object
    {
        $params = $request->only(['id','type','style','title','image_url','updated_at']);

        if (empty($params)){
            return $this->codeError([], 1022, '参数错误');

        }

        //判断标签名称去重
        $whereNotId = [];
        $whereOrOne = [];
        if (!empty($params['id'])) {
            $whereNotId = [$params['id']];
        }

        if (!empty($params['title'])) {
            $whereOrOne = $params['title'];
        }

        $tagTran = PosterModel::getOneByDeWeight($whereNotId, $whereOrOne, $params['style']);
        if (!empty($tagTran)) {
            return $this->codeError([], 1002, '名称重复！');

        }

        if (!empty($params['image_url'])){
            $params['updated_at'] = time();

        }

        //数据库操作
        if (!empty($params['id'])){
            //修改
            PosterModel::updateSingle(['id'=> $params['id']], $params);

        }else{
            //新增
            $params['created_at'] = time();
            PosterModel::insertSingle($params);

        }

        return $this->codeSuccess();

    }

    /**
     * 标签维护-删除标签
     * @return object|null
     */
    public function poster_delete(Request $request): object
    {
        $params = $request->only(['id']);

        if (empty($params['id'])){
            return $this->codeError([], 1024, '参数错误');

        }

        //用户管理添加/修改
        $delete['deleted_at'] = time();
        PosterModel::updateSingle(['id'=> $params['id']], $delete);
        return $this->codeSuccess();

    }

    /**
     * 标签维护
     * @return object|null
     */
    public function forbid(Request $request): object
    {
        $params = $request->only(['page', 'limit']);

        $tag = ForbidModel::getPage(['deleted_at'=> 0], $params['limit'] ?? 15);

        return $this->codeSuccess(FormatBase::listData($tag));
    }

    /**
     * 标签维护-添加/修改
     * @return object|null
     */
    public function forbid_update(Request $request): object
    {
        $params = $request->only(['id','name']);

        if (empty($params)){
            return $this->codeError([], 1022, '参数错误');

        }

        //判断标签名称去重
        $whereNotId = [];
        $whereOrOne = [];
        if (!empty($params['id'])) {
            $whereNotId = [$params['id']];
        }

        if (!empty($params['name'])) {
            $whereOrOne = $params['name'];
        }

        $tagTran = ForbidModel::getOneByDeWeight($whereNotId, $whereOrOne);
        if (!empty($tagTran)) {
            return $this->codeError([], 1002, '名称重复！');

        }

        //数据库操作
        if (!empty($params['id'])){
            //修改
            $params['updated_at'] = time();
            ForbidModel::insertSingle($params);

        }else{
            //新增
            $params['created_at'] = time();
            ForbidModel::insertSingle($params);

        }

        return $this->codeSuccess();

    }

    /**
     * 标签维护-删除标签
     * @return object|null
     */
    public function forbid_delete(Request $request): object
    {
        $params = $request->only(['id']);

        if (empty($params['id'])){
            return $this->codeError([], 1024, '参数错误');

        }

        //用户管理添加/修改
        $delete['deleted_at'] = time();
        ForbidModel::updateSingle(['id'=> $params['id']], $delete);
        return $this->codeSuccess();

    }
}
